package hydrap2p.speedlimiter;

import java.util.concurrent.Semaphore;

public class Transfer {
	private Semaphore busy;
	private int counter;
	
	public Transfer(int counter)
	{
		busy=new Semaphore(1);
		this.counter=counter;
	}
	
	/**
	 * Start blocking this transfer until it's finished
	 */
	public void start()
	{
		if (counter==0)
			return;
		try {
			busy.acquire();
			busy.acquire();
		} catch (InterruptedException e) {
		}
	}
	
	public int getRemaining()
	{
		synchronized(this)
		{
			return counter;
		}
	}
	
	/**
	 * Decreases the amount left and returns how much was actually decremented
	 * @param amount
	 * @return
	 */
	public int decrease(int amount)
	{
		int ret=0;
		synchronized(this)
		{
			if (amount<counter)
			{
				ret=amount;
				counter-=amount;
			}
			else
			{
				ret=counter;
				counter=0;
				busy.release();
			}
		}
		return ret;
	}
	
	public void cancel()
	{
		busy.release();
	}
}
